package com.xxxx.dao.impl;

import com.xxxx.dao.BaseDao;
import com.xxxx.dao.StudentDao;
import com.xxxx.entity.Student;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class StudentDaoImpl extends BaseDao implements StudentDao {
    @Override
    public int save(Student student) throws Exception {
        String sql="insert into student(sno,sname,sex,phone,address,birthday,email) values(?,?,?,?,?,?,?)";
        //return this.update(sql,student.getSno(),student.getSname(),student.getSex(),student.getPhone(),student.getAddress(),student.getBirthday(),student.getEmail());
        Object[] params={
                student.getSno(),
                student.getSname(),
                student.getSex(),
                student.getPhone(),
                student.getAddress(),
                student.getBirthday(),
                student.getEmail()
        };
        return this.update(sql,params);
    }

    @Override
    public int del(int sno) throws Exception {
        String sql="delete from student where sno=?";
        return this.update(sql,sno);
    }

    @Override
    public int update(Student student) throws Exception {
        String sql="update student set sname=?,sex=?,phone=?,address=?,birthday=?,email=? where sno=?";
        //return this.update(sql,student.getSname(),student.getSno());
        Object[] params={
                student.getSno(),
                student.getSname(),
                student.getSex(),
                student.getPhone(),
                student.getAddress(),
                student.getBirthday(),
                student.getEmail()
        };
        return this.update(sql,params);
    }

    @Override
    public ArrayList<Student> getAll() throws Exception {
        ArrayList<Student> list;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
            list = new ArrayList<>();
            conn=getConnection();
            String sql="select * from student";
            pstmt=conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next())
            {
                Student s=new Student();
                s.setSno(rs.getInt("sno"));
                s.setSname(rs.getString("sname"));
                s.setSex(rs.getString("sex"));
                s.setPhone(rs.getString("phone"));
                s.setAddress(rs.getString("address"));
                s.setBirthday(rs.getDate("birthday"));
                s.setEmail(rs.getString("email"));
                list.add(s);
            }
        } finally {
            close(rs,pstmt,conn);
        }
        return list;
    }
}
